"""
    This file is part of django-simp.

    django-simp is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    django-simp is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with django-simp.  If not, see <http://www.gnu.org/licenses/>.
"""

import sys, os, Image, uuid, shutil

from django.core import serializers
from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.shortcuts import render_to_response, get_object_or_404
from django.template.loader import render_to_string
from django.contrib.auth.decorators import user_passes_test
from django.utils import simplejson 
from django.core.paginator import Paginator, InvalidPage

#from SimpleJSONRPCServer import SimpleJSONRPCDispatcher

import settings

from simpdemo.settings import *
from simpdemo.models import *
from simp.models import Instance
    
#@user_passes_test(lambda u: u.has_perm('simp.use'), login_url=settings.LOGIN_URL)
def select(request):
    vars = {}
    vars["demoImages"] = DemoImage.objects.all()
    return render_to_response('simpdemo/select.html', vars)

def init_simp(request):
    # load image id from post and operation
    instId = str(uuid.uuid4())
    demoFile = DemoImage.objects.get(pk=request.POST["id"])
    simpInstance = Instance();
    simpInstance.id = instId
    simpInstance.session = request.COOKIES[settings.SESSION_COOKIE_NAME];
    simpInstance.embedded = False;
    simpInstance.image = demoFile.get_image_filename();
    simpInstance.preset = None;
    simpInstance.module = None;
    simpInstance.callback = "/simpdemo/gallery/add?image=%s.jpg&demoImage=%s" % (instId, request.POST["id"]) 
    simpInstance.save_as = SIMPDEMO_GALLERYPATH + instId + ".jpg"
    simpInstance.save();
    request.session['simp_instance'] = simpInstance.id;
    request.session.save();
    vars = {}
    vars["callback"] = "/simp/";
    return HttpResponse(simplejson.dumps(vars))

#@user_passes_test(lambda u: u.has_perm('simp.use'), login_url=settings.LOGIN_URL)
def gallery_view(request, demoImageId, page):
    vars = {}
    if (demoImageId == -1):
        imagePage = Paginator(GalleryImage.objects.all(), 10).page(page)
    else:
        imagePage = Paginator(GalleryImage.objects.filter(demoImage=demoImageId), 10).page(page)
        vars["demoImage"] = DemoImage.objects.get(pk=demoImageId)
    vars["images"] = imagePage.object_list
    vars["demoImageId"] = demoImageId
    if imagePage.has_previous():
        vars["prefPage"] = imagePage.previous_page_number()
    if imagePage.has_next():
        vars["nextPage"] = imagePage.next_page_number()
    return render_to_response('simpdemo/gallery_view.html', vars)

def gallery_main(request):
    return gallery_view(request, -1, 1)

def gallery_detail(request, imageId):
    #paginator = Paginator(Article.objects.all(), 5)
    image = GalleryImage.objects.get(pk=imageId)
    try: 
        nextId = GalleryImage.objects.filter(pk__gt=image.pk).order_by("pk")[0].pk
    except:
        nextId = -1
    try:   
        prevId = GalleryImage.objects.exclude(pk__gt=(image.pk-1)).order_by("-pk")[0].pk
    except:
        prevId = -1
    vars = {"image": image};
    if nextId > -1:
        vars["nextId"] = nextId
    if prevId > -1:
        vars["prevId"] = prevId
    return render_to_response('simpdemo/gallery_detail.html', vars)

def gallery_add(request):
    if len(request.POST):
        if request.POST.get("id", False) and request.POST.get("desc", False):
            image = GalleryImage.objects.get(pk=request.POST["id"])
            image.desc = request.POST["desc"]
            image.save()
            vals = {"callback": "/simpdemo/gallery/view/%s/" % request.POST["id"]}
            return HttpResponse(simplejson.dumps(vals))
    else:
        if request.GET.get("image", False) and request.GET.get("demoImage", False):
            image = None
            try:
                image = GalleryImage.objects.get(image="simpdemo/gallery/" + request.GET["image"])
            except:
                image = GalleryImage(image="simpdemo/gallery/" + request.GET["image"])
                image.demoImage = DemoImage.objects.get(pk=request.GET["demoImage"]);
                image.desc = "a modified image from the demo image with the title: %s" % image.demoImage.title
                image.save()
            vars = {"galleryImage": image}
            return render_to_response('simpdemo/gallery_add.html', vars)
        else:
            return HttpResponse("<h1>invalid request</h1>");